//
//  userAccount.swift
//  新浪微博
//
//  Created by yzl on 15/7/31.
//  Copyright © 2015年 yjc. All rights reserved.
//

import UIKit
/// 用户模型
class userAccount: NSObject {
// 用户是否登录标记
    class var userLogin: Bool {
        return shareAccount != nil
    }
    
// 定义属性
    var access_token:String?
    // 这个时间是数值型不是字符串
    var expires_in: NSTimeInterval = 0 {
        //set方法重新赋值
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
/// 过期日期
    var expiresDate:NSDate?
/// 当前授权用户的uid
    var uid:String?
/// 显示名称
    var name:String?
/// 用户头像地址
    var avatar_large:String?
/// 重写init方法
    init(dict: [String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
       userAccount.UserAccount = self
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
/// 描述对象信息
 override var description: String {
        let properties = ["access_token","expires_in","uid","expiresDate","name", "avatar_large"]
        return "\(dictionaryWithValuesForKeys(properties))"
  
    }
    
    /// 加载用户信息 － 调用方法，异步获取用户附加信息，保存当前用户信息
    func loadUserInfo(finished: (error: NSError?) -> ()) {
        NetworkTools.sharedNetworkTools.loadUserInfo(uid!) { (result, error) -> () in
            if error != nil {
                // 提示：error一定要传递！
                finished(error: error)
                return
            }
            
            // 设置用户信息
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            // 保存用户信息
            self.saveAccount()
            
            // 完成回调
            finished(error: nil)
        }
    }
    
   // MARK :归档解档
/// 获取归档路径
    static private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    /// 保存用户的帐号
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: userAccount.accountPath)
    }
    /// 加载读取用户信息
    // 用一个属性记录保存用户的账户信息
     static var UserAccount:userAccount?
    // 类函数可以改造成累属性
    class  var shareAccount :userAccount? {
    if UserAccount == nil {
        UserAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath)as?userAccount
        
    }
    if let date = UserAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending {
        // 如果已经过期，需要清空账号记录
        UserAccount = nil
    }
    return UserAccount
    
    }
    
    // MARK :归档-> 将自定义对象转换成二进制数据保存到磁盘
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    /// `解`档 -> 恢复 将二进制数据从磁盘恢复成自定义对象
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
}
